
package com.chinacreator.c2etcd;
import com.google.gson.Gson;
import io.etcd.jetcd.ByteSequence;
import io.etcd.jetcd.Client;
import io.etcd.jetcd.KV;
import io.etcd.jetcd.KeyValue;
import io.etcd.jetcd.kv.GetResponse;
import io.etcd.jetcd.watch.WatchResponse;
import java.nio.charset.Charset;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;

/**
 * @Author: jack.liang
 **/
public class TestEtcd {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        EtcdClient etcdClient = EtcdClientFactory.getInstance().connect("-config",
                "http://10.47.140.59:2379",
                true, false);

        // create client
        Client client = Client.builder().endpoints("http://10.47.140.59:2379").build();
        KV kvClient = client.getKVClient();

        ByteSequence key = ByteSequence.from("test_key".getBytes());
        ByteSequence value = ByteSequence.from("test_value".getBytes());

// put the key-value
        kvClient.put(key, value).get();

// get the CompletableFuture
        CompletableFuture<GetResponse> getFuture = kvClient.get(key);

// get the value from CompletableFuture
        GetResponse response = getFuture.get();

// delete the key
        kvClient.delete(key).get();


//        KV etcdClient = client.getKVClient();
        try {
//            etcdClient.put(ByteSequence.from("/test/etcd", Charset.defaultCharset()),ByteSequence.from("public".getBytes()));
//            GetResponse getResponse = etcdClient.get(ByteSequence.from("/test/etcd/".getBytes())).get();
            long l1 = System.currentTimeMillis();
            etcdClient.putKey("/test/etcd","public");
            long l2 = System.currentTimeMillis();
            System.out.println("time\t:"+(l2-l1) + "\n");

            long l3 = System.currentTimeMillis();
            KeyValue keyValue = etcdClient.getKey("/test/etcd");
            long l4 = System.currentTimeMillis();
            System.out.println("time\t:" + (l4-l3 )+ "\n");

            System.out.println(keyValue.getValue().toString(Charset.defaultCharset()));
//            WatcherListener watcherListener = new WatcherListener() {
//                @Override
//                public void watcherKeyChanged(EtcdClient etcdClient, EtcdChangedEvent event) throws Exception {
//                System.out.println(event);
//                }
//            };
            etcdClient.addWatcherListener("/test/etcd", new Consumer<WatchResponse>() {
                @Override
                public void accept(WatchResponse watchResponse) {
                    System.out.println(new Gson().toJson(watchResponse.getEvents()));
                }
            });

            etcdClient.putKey("/test/etcd","helloworld");
            etcdClient.deleteKey("/test/etcd");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
